<template>
  <div v-loading="dataLoading || optionsLoading" class="app-container">
    <div class="data-content">
      <div class="action-content">
        <el-row :gutter="10">
          <el-col :span="14">
            <span style="font-size: x-large; margin-right: 10px">{{ $t('skuShelve') }}</span>
            <span style="color: grey">{{ $t('shelve.orderAndBoxNo') }} {{ boxInfo.orderNo }} / {{ boxInfo.boxNo }}</span>
          </el-col>
          <el-col :span="9">
            <el-button :disabled="currentTab === '1' || selectedList.length === 0" type="primary" style="float: right" @click="confirmShelve">{{ $t('shelve.confirm') }}</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" style="margin-top: 10px">
          <el-col :span="24">
            <el-input ref="skuCodeInput" v-model="skuCode" :placeholder="$t('shelve.pleaseScanSku')" clearable @keyup.enter.native.prevent="handleScanSku">
              <i slot="prefix" class="el-icon-full-screen scan-icon" />
            </el-input>
          </el-col>
        </el-row>
      </div>
      <el-tabs v-model="currentTab" @tab-click="handleTabSwitch">
        <el-tab-pane :label="$t('shelve.statusNew')" name="0" />
        <el-tab-pane :label="$t('shelve.statusFinished')" name="1" />
      </el-tabs>
      <div class="table-content">
        <el-table ref="mainTable" :data="tableData" height="100%" style="width: 100%" stripe highlight-current-row @selection-change="handleSelectionChange" @current-change="handleCurrentChange">
          <el-table-column v-if="currentTab === '0'" type="selection" width="55" align="center" />
          <el-table-column label="SKU" min-width="150" prop="skuCode" align="center" />
          <el-table-column :label="$t('shelve.receiveStatus')" min-width="100" prop="receiveStatus" align="center">
            <template v-slot="{ row }">
              {{ row.receiveStatus === 0 ? $t("warehousingLang.firstArrival") : $t("warehousingLang.toTheWarehouseAgain") }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('shelve.packagingType')" min-width="150" prop="packagingType" align="center">
            <template v-slot="{ row }">
              {{ $t('warehousingLang.' + packagingTypeEnum.find(item => item.value === row.packagingType).title) }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('shelve.realSize')" min-width="150" prop="realSize" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.skuLength }}*{{ scope.row.skuWidth }}*{{ scope.row.skuHeight }} CM</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('shelve.realWeight')" prop="realWeight" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.skuWeight }} KG</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('shelve.forecastNum')" prop="preSkuNum" min-width="100" align="center" />
          <el-table-column :label="$t('shelve.receiptNum')" prop="receiptNum" min-width="100" align="center" />
          <el-table-column prop="locationCode" min-width="250" align="center">
            <template slot="header">
              <div v-if="currentTab === '0'">
                <span style="color: red">*</span>{{ $t('shelve.referLocationAndNum') }}
              </div>
              <span v-else>{{ $t('shelve.locationAndNum') }}</span>
            </template>
            <template slot-scope="scope">
              <div v-if="currentTab === '1'">
                <el-row v-for="(location, i) in scope.row.locations" :key="i" :gutter="5" style="margin-bottom: 2px">
                  <span>{{ location.locationCode }} * {{ location.shelveNum }}</span>
                </el-row>
              </div>
              <div v-else>
                <el-row v-for="(location, i) in scope.row.locations" :key="i" :gutter="5" style="margin-bottom: 2px">
                  <el-col :span="14">
<!--                    <el-select v-model="location.locationCode" filterable remote :remote-method="filterSkuLocation" clearable @focus="skuLocationFocus(scope.row.referLocationCode)">-->
<!--                      <el-option-group v-for="group in skuLocationOptions" :key="group.label" :label="group.label">-->
<!--                        <el-option v-for="item in group.options" :key="item.value" :value="item.value" :label="item.value">-->
<!--                          <span style="float: left">{{ item.value }}</span>-->
<!--                          <span style="float: right; color: #8492a6; font-size: 13px">{{ $t('locationLang.' + item.label) }}</span>-->
<!--                        </el-option>-->
<!--                      </el-option-group>-->
<!--                    </el-select>-->
                    <el-input v-model="scope.row.locationCode" />
                  </el-col>
                  <el-col :span="10" style="display: flex">
                    <el-input v-model="location.shelveNum" style="flex: 1; margin-right: 4px" />
                    <el-button v-if="scope.row.locations.length > 1" type="text" icon="el-icon-remove-outline" @click="scope.row.locations.splice(i, 1)" />
                  </el-col>
                </el-row>
                <el-row :gutter="5">
                  <el-col :span="14">
                    <el-button type="text" icon="el-icon-plus" @click="scope.row.locations.push({})">{{ $t('inbound.addLocation') }}</el-button>
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { confirmShelve, getBoxInfo } from '@/api/business/warehouseManage/shelve';
import { scanFail, scanSuccess } from '@/utils/validate';
import { locationPickTypeDict, packageTypeDict } from '@/utils/dictData';
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils';
import { getDepotLocationForFree } from '@/api/business/depotManage/location';

export default {
  name: 'SkuShelve',
  components: {},
  data() {
    return {
      dataLoading: false,
      optionsLoading: false,
      currentTab: '0',
      boxInfo: {},
      skuCode: null,
      packagingTypeEnum: getDictOptionList(packageTypeDict),
      currentSku: null,
      tableData: [],
      selectedList: [],
      locationList: [],
      skuLocationOptions: [],
    }
  },
  created() {
    this.getDepotLocationForFree()
    this.getBoxInfo(this.$route.params.boxNo)
  },
  methods: {
    handleTabSwitch() {
      this.dataLoading = true
      this.tableData = this.boxInfo.detailDTOList.filter(item => {
        if (this.currentTab === '0') {
          return item.shelfStockingNum === 0
        } else {
          return item.shelfStockingNum > 0
        }
      })
      if (this.currentTab === '0') {
        const selectedListTemp = this.selectedList;
        const currentSkuTemp = this.currentSku;
        this.$nextTick(() => {
          selectedListTemp.forEach(row => this.$refs.mainTable.toggleRowSelection(row, true))
          this.$refs.mainTable.setCurrentRow(currentSkuTemp);
          this.dataLoading = false
        })
      } else {
        this.dataLoading = false
      }
    },
    scrollToCurrentRow() {
      this.$nextTick(() => {
        const currentRow = this.$refs.mainTable.$el.getElementsByClassName('current-row')[0]
        if (currentRow) {
          this.$refs.mainTable.bodyWrapper.scrollTo({ top: currentRow.offsetTop, behavior: 'smooth' })
        }
      })
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      if (this.currentTab === '0') {
        this.currentSku = currentRow
      }
    },
    handleScanSku() {
      this.currentSku = this.boxInfo.detailDTOList.find(item => item.shelfStockingNum === 0 && item.skuCode === this.skuCode)
      if (this.currentSku) {
        scanSuccess()
        this.currentTab = '0'
        this.selectedList.push(this.currentSku)
        this.handleTabSwitch();
        this.$nextTick(() => {
          this.scrollToCurrentRow()
        })
      } else {
        scanFail()
      }
      this.skuCode = null
      this.$refs.skuCodeInput.focus()
    },
    handleSelectionChange(rows) {
      if (this.currentTab === '0') {
        this.selectedList = rows;
      }
    },
    async getBoxInfo(boxNo) {
      this.dataLoading = true;
      await getBoxInfo({ boxNo: boxNo }).then((res) => {
        this.$refs.skuCodeInput.focus()
        res.data.detailDTOList.forEach(sku => {
          if (sku.shelfStockingNum > 0) {
            sku.locations = sku.stockBatchList?.map(stock => {
              return { locationCode: stock.locationCode, shelveNum: stock.skuNum }
            })
          } else {
            sku.locations = [{}]
          }
        })
        this.boxInfo = res.data;
        this.handleTabSwitch()
      }).finally(() => {
        this.dataLoading = false;
      })
    },
    async getDepotLocationForFree() {
      this.optionsLoading = true
      await getDepotLocationForFree({ freeFlag: 1, locationstatus: 1 }).then((res) => {
        this.locationList = res.data.resultList.map(item => {
          return { value: item.locationCode, label: getTitleByValue(getDictOptionList(locationPickTypeDict), item.pickType) }
        })
      }).finally(() => {
        this.optionsLoading = false;
      })
    },
    skuLocationFocus(referLocations) {
      const options0 = referLocations.map(item => {
        return {
          value: item.locationCode,
          label: getTitleByValue(getDictOptionList(locationPickTypeDict), item.pickType)
        }
      })
      const options1 = this.locationList.slice(0, 10)
      this.setSkuLocation(options0, options1)
    },
    filterSkuLocation(value) {
      const options0 = this.skuLocationOptions[0].options.filter(item => !value || item.value.toLowerCase().includes(value.toLowerCase()))
      const options1 = this.locationList.filter(item => !value || item.value.toLowerCase().includes(value.toLowerCase())).slice(0, 10)
      this.setSkuLocation(options0, options1)
    },
    setSkuLocation(options0, options1) {
      this.skuLocationOptions = [{
        label: this.$t('inbound.referLocation'),
        options: options0
      }, {
        label: this.$t('inbound.freeLocation'),
        options: options1
      }]
    },
    validate(sku) {
      return !sku.locations.find(item => !(item.shelveNum > 0 && item.locationCode))
    },
    confirmShelve() {
      if (this.selectedList.length <= 0) return
      const request = {
        fromTerminal: 0,
        orderId: this.boxInfo.orderId,
        orderInfoForShelveList: []
      }
      for (const sku of this.selectedList) {
        if (!this.validate(sku)) {
          this.$message.error(this.$t('pleaseCheck') + this.$t('required'))
          this.$refs.mainTable.setCurrentRow(sku);
          this.scrollToCurrentRow()
          return
        }
        request.orderInfoForShelveList = request.orderInfoForShelveList.concat(sku.locations.map(location => {
          return {
            boxId: this.boxInfo.boxId,
            skuId: sku.skuId,
            shelfStockingNum: location.shelveNum,
            locationCode: location.locationCode,
          }
        }))
      }
      this.dataLoading = true;
      confirmShelve(request).then((res) => {
        if (!res || res.returnCode !== 10000) return
        this.$confirm(this.$t('shelve.shelveSuccess'), '', {
          confirmButtonText: this.$t('shelve.continuScan'),
          cancelButtonText: this.$t('cancel'),
          type: 'success',
          center: true
        }).then(() => {
          this.$router.push({ name: 'ShelveScan' })
          this.confirmShelveSuccess()
        }).catch(() => {
          this.confirmShelveSuccess()
        });
      }).finally(() => {
        this.dataLoading = false;
      })
    },
    confirmShelveSuccess() {
      this.skuCode = null
      this.currentTab = '1'
      this.currentSku = null
      this.selectedList = []
      this.getBoxInfo(this.boxInfo.boxNo)
      this.getDepotLocationForFree()
      this.$nextTick(() => {
        this.$refs.mainTable.clearSelection();
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: auto;
}

.data-content{
  padding: 20px;
  flex: 1;
  border: 1px solid #e6ebf5;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  display: flex;
  flex-direction: column;
  min-height: 500px;
  overflow: hidden;

  .action-content {
    margin-bottom: 5px;

    ::v-deep .el-input__inner {
      height: 50px;
      padding-left: 45px;
    }

    .scan-icon {
      margin: 15px 15px 0 10px;
      font-size: 20px
    }
  }

  .table-content {
    flex: 1;
    overflow: hidden;
  }
}
</style>
